﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.RecordSiteQuery;
using MS.InformationManagement.DAL.RecordCenter;
using MS.InformationManagement.Support.Constants;
using Microsoft.SharePoint;
using MS.InformationManagement.Support;

namespace MS.InformationManagement.BLL.TRDSelector
{
    public class TRDSelector
    {

        public IEnumerable<Seccion> GetSecciones()
        {
            //string query = string.Format("<Where><IsNull><FieldRef Name='{0}' /></IsNull></Where>", CustomSiteColumns.FIELD_SECCION_PADRE_INTERNAL_NAME);
            //IEnumerable<Seccion> secciones = QueryRecordsSiteHelper<Seccion>.QueryRecordsEntitiesSite(GlobalConstants.LIST_BIBLIOTECA_SECCION, query, null);

            IEnumerable<Seccion> secciones = QueryRecordsSiteHelper<Seccion>.QueryRecordsAllEntitiesSite(GlobalConstants.LIST_BIBLIOTECA_SECCION, null);
            return secciones.OrderBy(x => x.Title);
        }

        public IEnumerable<Serie> GetSeries()
        {
            IEnumerable<Serie> series = QueryRecordsSiteHelper<Serie>.QueryAllRecords(GlobalConstants.LIST_BIBLIOTECA_SERIE, null);
            return series.OrderBy(x => x.Title);
        }

        public IEnumerable<TipoDocumental> GetAllDocumentalTypes()
        {
            IEnumerable<TipoDocumental> tipos = QueryRecordsSiteHelper<TipoDocumental>.QueryAllRecords(GlobalConstants.LIST_BIBLIOTECA_TIPOS_DOCUMENTALES, null);
            return tipos.OrderBy(x => x.Title);
        }

        public IEnumerable<Seccion> GetSubSecciones(int seccionId)
        {
            string query = string.Format("<Where><Eq><FieldRef Name='{0}' LookupId='TRUE'/><Value Type='LookUp'>{1}</Value></Eq></Where>", CustomSiteColumns.FIELD_SECCION_PADRE_INTERNAL_NAME, seccionId);
            IEnumerable<Seccion> subSeccion = QueryRecordsSiteHelper<Seccion>.QueryRecordsEntitiesSite(GlobalConstants.LIST_BIBLIOTECA_SECCION, query, null);
            return subSeccion;
        }

        public IEnumerable<Subserie> GetSubSeries(int serieId)
        {
            IEnumerable<Subserie> series = QueryRecordsSiteHelper<Subserie>.QueryRecordsChildEntitiesSite(GlobalConstants.LIST_BIBLIOTECA_SUBSERIE, serieId.ToString(), CustomSiteColumns.FIELD_SERIE);
            return series.OrderBy(x => x.Title);
        }

        public IEnumerable<Seccion> GetAllBrotherSubSections(int subSectionBrother)
        {
            var parentSectionEntity = QueryRecordsSiteHelper<Seccion>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_SECCION, subSectionBrother);
            if (parentSectionEntity.SecciónPadre == null)
                return null;
            int parentSection = parentSectionEntity.SecciónPadre.Id.Value;
            return GetSubSecciones(parentSection);
        }

        public IEnumerable<Subserie> GetAllBrotherSubSeries(int subSerieBrother)
        {
            int parentSerie = QueryRecordsSiteHelper<Subserie>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_SUBSERIE, subSerieBrother).Serie.Id.Value;
            return GetSubSeries(parentSerie);
        }

        public IEnumerable<TipoDocumental> GetDocumentalTypes(int seccionID, int subseccionID, int serieID, int subSerieID)
        {
            IEnumerable<TipoDocumental> foundElements = null;
            string caml = string.Format(@"<Where>
              <And>
                 <Eq>
                    <FieldRef Name='SeccionTRD' LookupId='TRUE'/>
                    <Value Type='Lookup'>{0}</Value>
                 </Eq>
                 <And>
                    <Eq>
                       <FieldRef Name='SubseccionTRD' LookupId='TRUE'/>
                       <Value Type='Lookup'>{1}</Value>
                    </Eq>
                    <And>
                       <Eq>
                          <FieldRef Name='SerieTRD' LookupId='TRUE'/>
                          <Value Type='Lookup'>{2}</Value>
                       </Eq>
                       <And>
                           <Eq>
                              <FieldRef Name='SubserieTRD' LookupId='TRUE'/>
                              <Value Type='Lookup'>{3}</Value>
                           </Eq>
                           <Eq>
                              <FieldRef Name='IsActive' />
                              <Value Type='Boolean'>1</Value>
                           </Eq>
                       </And> 
                    </And>
                 </And>
              </And>
           </Where>", seccionID, subseccionID, serieID, subSerieID);

            ItemTRD foundItem = QueryRecordsSiteHelper<ItemTRD>.QueryRecordsEntitiesSite(GlobalConstants.LIST_BIBLIOTECA_TRD, caml, new Nullable<uint>()).FirstOrDefault();

            if (foundItem != default(ItemTRD)) { foundElements = foundItem.TiposDocumentales; }

            return foundElements;
        }

        public bool BelongsToCurrentTRD(int seccionID, int subseccionID, int serieID, int subSerieID, int documentalTypeId)
        {
            bool belongsToCurrentTRD = false;
            string recordSiteUrl = ConfigurationHelper.GetInstance().ConfigItems[GlobalConstants.SITE_RECORDS_URL];
            using (SPSite site = new SPSite(recordSiteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList targetList = web.Lists.TryGetList(GlobalConstants.LIST_BIBLIOTECA_TRD);

                    string oldElementsCaml = string.Format(@"<Where>
                      <And>
                         <Eq>
                            <FieldRef Name='SeccionTRD' LookupId='TRUE'/>
                            <Value Type='Lookup'>{0}</Value>
                         </Eq>
                         <And>
                            <Eq>
                               <FieldRef Name='SubseccionTRD' LookupId='TRUE'/>
                               <Value Type='Lookup'>{1}</Value>
                            </Eq>
                            <And>
                               <Eq>
                                  <FieldRef Name='SerieTRD' LookupId='TRUE'/>
                                  <Value Type='Lookup'>{2}</Value>
                               </Eq>
                               <And>
                                   <Eq>
                                      <FieldRef Name='SubserieTRD' LookupId='TRUE'/>
                                      <Value Type='Lookup'>{3}</Value>
                                   </Eq>
                                   <And>                           
                                       <Eq>
                                          <FieldRef Name='IsActive' />
                                          <Value Type='Boolean'>0</Value>
                                       </Eq>
                                       <Eq>
                                          <FieldRef Name='TiposDocumentales' LookupId='TRUE' />
                                          <Value Type='Lookup'>{4}</Value>
                                      </Eq>
                                    </And>
                               </And> 
                            </And>
                         </And>
                      </And>
                   </Where>", seccionID, subseccionID, serieID, subSerieID, documentalTypeId);
                    string currentElementsCaml = string.Format(@"<Where>
                      <And>
                         <Eq>
                            <FieldRef Name='SeccionTRD' LookupId='TRUE'/>
                            <Value Type='Lookup'>{0}</Value>
                         </Eq>
                         <And>
                            <Eq>
                               <FieldRef Name='SubseccionTRD' LookupId='TRUE'/>
                               <Value Type='Lookup'>{1}</Value>
                            </Eq>
                            <And>
                               <Eq>
                                  <FieldRef Name='SerieTRD' LookupId='TRUE'/>
                                  <Value Type='Lookup'>{2}</Value>
                               </Eq>
                               <And>
                                   <Eq>
                                      <FieldRef Name='SubserieTRD' LookupId='TRUE'/>
                                      <Value Type='Lookup'>{3}</Value>
                                   </Eq>
                                   <And>                           
                                       <Eq>
                                          <FieldRef Name='IsActive' />
                                          <Value Type='Boolean'>1</Value>
                                       </Eq>
                                       <Eq>
                                          <FieldRef Name='TiposDocumentales' LookupId='TRUE' />
                                          <Value Type='Lookup'>{4}</Value>
                                      </Eq>
                                    </And>
                               </And> 
                            </And>
                         </And>
                      </And>
                   </Where>", seccionID, subseccionID, serieID, subSerieID, documentalTypeId);
                    SPListItemCollection oldItems = targetList.GetItems(new SPQuery { Query = oldElementsCaml });
                    SPListItemCollection currentItems = targetList.GetItems(new SPQuery { Query = currentElementsCaml });
                    
                    belongsToCurrentTRD = oldItems.Count == 0 || (oldItems.Count > 0 && currentItems.Count > 0);

                }
            }
            return belongsToCurrentTRD;
        }

        public Seccion GetSeccion(string sectionName) {
            Seccion entity = null;
            string caml = string.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where>", sectionName);
            entity = QueryRecordsSiteHelper<Seccion>.QueryRecordsEntitiesSite(GlobalConstants.LIST_BIBLIOTECA_SECCION, caml, new Nullable<uint>()).FirstOrDefault();
            if (entity == default(Seccion)) { throw new Exception(string.Format("No se encuentra una seccion configurada con el nombre {0}", sectionName)); }
            return entity;
        }

        public Seccion GetSeccionForCurrentUser() {
            Seccion entity = null;
            string currentSectionName = PeopleHelper.GetPropertyUserProfile(GlobalConstants.UP_DEPARTMENT, SPContext.Current.Web.CurrentUser.LoginName);
            string caml = string.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where>", currentSectionName);
            entity = QueryRecordsSiteHelper<Seccion>.QueryRecordsEntitiesSite(GlobalConstants.LIST_BIBLIOTECA_SECCION, caml, new Nullable<uint>()).FirstOrDefault();
            if (entity == default(Seccion)) { throw new Exception(string.Format("No se encuentra una seccion configurada con el nombre {0}", currentSectionName)); }
            return entity;
        }
    }
}
